import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'package:flutter/rendering.dart';
import 'dart:typed_data';
import 'package:image_picker/image_picker.dart';
import 'package:flutter/services.dart';
import 'dart:io';
import 'dart:math';
import 'package:permission_handler/permission_handler.dart';
import 'package:share_plus/share_plus.dart';
import 'package:path_provider/path_provider.dart';
import '../models/hexagram.dart';
import '../constants/colors.dart';
import '../widgets/gradient_background.dart';
import '../widgets/app_button.dart';

class SharePosterPage extends StatefulWidget {
  final Hexagram hexagram;
  
  const SharePosterPage({Key? key, required this.hexagram}) : super(key: key);

  @override
  State<SharePosterPage> createState() => _SharePosterPageState();
}

class _SharePosterPageState extends State<SharePosterPage> {
  final GlobalKey _globalKey = GlobalKey();
  bool _isLoading = false;
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GradientBackground(
        child: SafeArea(
          child: Column(
            children: [
              _buildHeader(),
              Expanded(
                child: SingleChildScrollView(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      children: [
                        RepaintBoundary(
                          key: _globalKey,
                          child: _buildPoster(),
                        ),
                        const SizedBox(height: 24),
                        _buildButtons(),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        children: [
          IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: AppColors.textPrimary),
            onPressed: () => Navigator.pop(context),
          ),
          const Expanded(
            child: Center(
              child: Text(
                '分享海报',
                style: TextStyle(
                  color: AppColors.textPrimary,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          const SizedBox(width: 48), // 平衡布局
        ],
      ),
    );
  }

  Widget _buildPoster() {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        children: [
          _buildPosterHeader(),
          _buildPosterContent(),
          _buildPosterFooter(),
        ],
      ),
    );
  }

  Widget _buildPosterHeader() {
    return Container(
      padding: const EdgeInsets.all(16.0),
      decoration: const BoxDecoration(
        color: AppColors.primaryGradientStart,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      child: Row(
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: Colors.white,
              shape: BoxShape.circle,
              border: Border.all(color: Colors.white, width: 2),
            ),
            child: const Center(
              child: Icon(
                Icons.auto_awesome,
                color: AppColors.primaryGradientStart,
                size: 24,
              ),
            ),
          ),
          const SizedBox(width: 12),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '梅花易数',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 4),
                Text(
                  '传统智慧，现代解析',
                  style: TextStyle(
                    color: Colors.white70,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPosterContent() {
    return Container(
      padding: const EdgeInsets.all(24.0),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Center(
            child: Text(
              widget.hexagram.name,
              style: const TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.bold,
                color: AppColors.textPrimary,
              ),
            ),
          ),
          const SizedBox(height: 24),
          Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  widget.hexagram.upperSymbol,
                  style: const TextStyle(
                    fontSize: 64,
                    color: AppColors.primaryGradientStart,
                  ),
                ),
                const SizedBox(width: 16),
                Text(
                  widget.hexagram.lowerSymbol,
                  style: const TextStyle(
                    fontSize: 64,
                    color: AppColors.primaryGradientStart,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 24),
          const Divider(),
          const SizedBox(height: 16),
          const Text(
            '卦辞',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: AppColors.primaryGradientStart,
            ),
          ),
          const SizedBox(height: 12),
          Text(
            widget.hexagram.description,
            style: const TextStyle(
              fontSize: 16,
              height: 1.8,
              color: AppColors.textPrimary,
            ),
          ),
          const SizedBox(height: 24),
          const Text(
            '卦象解析',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: AppColors.primaryGradientStart,
            ),
          ),
          const SizedBox(height: 12),
          const Text(
            '此卦象表明当前形势正处于变化之中，需要保持冷静和耐心。上卦与下卦的组合显示出内在与外在的关系，提醒您注意内心的声音与外部环境的互动。',
            style: TextStyle(
              fontSize: 16,
              height: 1.8,
              color: AppColors.textPrimary,
            ),
          ),
          const SizedBox(height: 24),
          const Text(
            '现代启示',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: AppColors.primaryGradientStart,
            ),
          ),
          const SizedBox(height: 12),
          const Text(
            '事业：保持稳健前行，避免冒进\n'
            '健康：注意调节作息，保持平和心态\n'
            '感情：坦诚沟通，相互理解\n'
            '财运：稳中求进，避免投机',
            style: TextStyle(
              fontSize: 16,
              height: 1.8,
              color: AppColors.textPrimary,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPosterFooter() {
    return Container(
      padding: const EdgeInsets.all(16.0),
      decoration: const BoxDecoration(
        color: Color(0xFFF5F5F5),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(16),
          bottomRight: Radius.circular(16),
        ),
      ),
      child: Row(
        children: [
          Container(
            width: 80,
            height: 80,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey.shade300),
            ),
            child: const Center(
              child: Text(
                'QR\nCode',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: AppColors.textPrimary,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          const SizedBox(width: 16),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '扫描二维码',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: AppColors.textPrimary,
                  ),
                ),
                SizedBox(height: 4),
                Text(
                  '下载梅花易数APP，获取更多卦象解析',
                  style: TextStyle(
                    fontSize: 14,
                    color: AppColors.textSecondary,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildButtons() {
    return AppPrimaryButton(
      text: '分享',
      isLoading: _isLoading,
      onPressed: _sharePoster,
    );
  }

  // 捕获海报图片并返回图片数据
  Future<Uint8List?> _capturePosterImage({double pixelRatio = 4.0}) async {
    try {
      print('开始捕获海报图片...');
      
      // 将RepaintBoundary转换为图片
      RenderRepaintBoundary boundary = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      
      // 增加延迟，确保UI已经完全渲染
      await Future.delayed(const Duration(milliseconds: 500));
      
      // 使用指定的像素比率
      ui.Image image = await boundary.toImage(pixelRatio: pixelRatio);
      print('图片已捕获，尺寸: ${image.width}x${image.height}');
      
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      
      if (byteData != null) {
        Uint8List pngBytes = byteData.buffer.asUint8List();
        print('图片数据已获取，大小: ${pngBytes.length} 字节');
        return pngBytes;
      } else {
        print('无法获取图片数据');
        return null;
      }
    } catch (e) {
      print('捕获海报图片错误: $e');
      return null;
    }
  }

  // 保存海报到相册
  Future<void> _capturePoster() async {
    setState(() {
      _isLoading = true;
    });

    try {
      print('开始保存海报流程...');
      
      // 请求存储权限
      bool hasPermission = await _requestStoragePermission();
      if (!hasPermission) {
        setState(() {
          _isLoading = false;
        });
        return;
      }
      
      // 捕获图片
      Uint8List? imageData = await _capturePosterImage();
      if (imageData == null) {
        throw Exception('无法获取图片数据');
      }
      
      // 保存图片到文件
      String fileName = "梅花易数_${widget.hexagram.name}_${DateTime.now().millisecondsSinceEpoch}.png";
      final directory = await getApplicationDocumentsDirectory();
      final imagePath = '${directory.path}/$fileName';
      final imageFile = File(imagePath);
      
      // 写入图片数据
      await imageFile.writeAsBytes(imageData);
      print('图片已保存到应用文档目录: $imagePath');
      
      // 显示保存成功的提示
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('海报已保存到应用文档目录'),
          duration: Duration(seconds: 2),
        ),
      );
      
      // 提示用户如何将图片保存到相册
      _showSaveToGalleryDialog(imagePath);
      
    } catch (e) {
      print('保存海报错误: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('保存失败: ${e.toString().substring(0, min(50, e.toString().length))}')),
      );
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
  
  // 请求存储权限
  Future<bool> _requestStoragePermission() async {
    print('请求存储权限...');
    
    // 根据平台请求不同的权限
    if (Platform.isAndroid) {
      print('Android平台: 请求存储权限');
      
      // 尝试请求多种权限，以确保在不同Android版本上都能正常工作
      Map<Permission, PermissionStatus> statuses = await [
        Permission.storage,
        Permission.photos,
        Permission.mediaLibrary,
      ].request();
      
      print('权限状态: $statuses');
      
      // 检查是否有任何一个权限被授予
      bool anyGranted = statuses.values.any((status) => status.isGranted);
      bool anyPermanentlyDenied = statuses.values.any((status) => status.isPermanentlyDenied);
      
      if (anyGranted) {
        print('至少一个权限已授予');
        return true;
      } else {
        print('所有权限都被拒绝');
        if (anyPermanentlyDenied) {
          _showPermissionDialog();
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('需要存储权限才能保存图片，请允许权限请求')),
          );
        }
        return false;
      }
    } else if (Platform.isIOS) {
      print('iOS平台: 请求相册权限');
      
      // iOS使用photos权限
      var status = await Permission.photos.request();
      print('相册权限状态: $status');
      
      if (status.isGranted) {
        print('相册权限已授予');
        return true;
      } else {
        print('相册权限被拒绝');
        if (status.isPermanentlyDenied) {
          _showPermissionDialog();
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('需要相册权限才能保存图片')),
          );
        }
        return false;
      }
    } else {
      // 其他平台直接返回true
      print('其他平台，假设已有权限');
      return true;
    }
  }
  
  // 显示保存到相册的对话框
  void _showSaveToGalleryDialog(String imagePath) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('保存到相册'),
          content: const Text('海报已保存到应用内。您想将其保存到相册吗？'),
          actions: <Widget>[
            TextButton(
              child: const Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: const Text('保存到相册'),
              onPressed: () {
                Navigator.of(context).pop();
                _saveToGallery(imagePath);
              },
            ),
          ],
        );
      },
    );
  }
  
  // 保存到相册
  Future<void> _saveToGallery(String imagePath) async {
    try {
      // 使用Share.shareXFiles来提供保存到相册的选项
      await Share.shareXFiles(
        [XFile(imagePath)],
        text: '梅花易数 - ${widget.hexagram.name}卦象解析',
        subject: '梅花易数卦象分享',
      );
    } catch (e) {
      print('保存到相册错误: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('保存到相册失败: ${e.toString().substring(0, min(50, e.toString().length))}')),
      );
    }
  }

  // 分享海报
  Future<void> _sharePoster() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      // 捕获图片
      Uint8List? imageData = await _capturePosterImage(pixelRatio: 3.0);
      if (imageData == null) {
        throw Exception('无法获取图片数据');
      }
      
      // 创建临时文件
      final tempDir = await getTemporaryDirectory();
      final fileName = "梅花易数_${widget.hexagram.name}_${DateTime.now().millisecondsSinceEpoch}.png";
      final tempFile = File('${tempDir.path}/$fileName');
      
      // 写入图片数据
      await tempFile.writeAsBytes(imageData);
      
      // 使用share_plus分享图片
      await Share.shareXFiles(
        [XFile(tempFile.path)],
        text: '梅花易数 - ${widget.hexagram.name}卦象解析',
        subject: '梅花易数卦象分享',
      );
    } catch (e) {
      print('分享海报错误: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('分享失败: ${e.toString().substring(0, min(50, e.toString().length))}')),
      );
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
  
  // 显示权限提示对话框
  void _showPermissionDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('需要相册权限'),
          content: const Text('保存海报需要访问您的相册权限。请在设置中允许应用访问相册。'),
          actions: <Widget>[
            TextButton(
              child: const Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: const Text('去设置'),
              onPressed: () async {
                Navigator.of(context).pop();
                // 使用permission_handler打开应用设置页面
                await openAppSettings();
              },
            ),
          ],
        );
      },
    );
  }
}